package com.sharemarking.wa.platform.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.Agreement;
import com.sharemarking.wa.common.entity.OrgMember;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.platform.dto.agreement.AgreementInfoDto;
import com.sharemarking.wa.platform.dto.agreement.OrgAgreementDto;
import com.sharemarking.wa.platform.mapper.*;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.REQUIRED_PARAMS_ERROR;

/**
 * @author dxy
 */
@Service
public class AgreementService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private AgreementMapper agreementMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private CompanyMapper companyMapper;

    public ResponseParams<?> getAgreementInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String agreementId = request.getParameter("agreementId");
        AgreementInfoDto agreementInfoDto = null;
        if (memberMapper.getRoleByMemberId(memberId) != 0 && memberMapper.getRoleByMemberId(memberId) != 1) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        if (StringUtils.isEmpty(agreementId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("agreementId"));
        }
        if(memberMapper.getRoleByMemberId(memberId)==0){
            agreementInfoDto= agreementMapper.getAgreementInfo(Integer.valueOf(agreementId), memberId);
        }else if (memberMapper.getRoleByMemberId(memberId)==1){
            agreementInfoDto= agreementMapper.getAgreementInfoByManageId(Integer.valueOf(agreementId), memberId);
        }
        if(new Date().getTime()>agreementInfoDto.getExpireDate()){
            agreementInfoDto.setExamState(3);
        }
        return ResponseParams.ok(agreementInfoDto);
    }


    public ResponseParams<?> getOrgAgreementList() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        Integer role = memberMapper.getRoleByMemberId(memberId);
        if (role != 0 && role != 1) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);
        if (!ObjectUtils.isEmpty(companyMapper.getCompany(memberId)))
        params.put("name", companyMapper.getCompany(memberId).getCompanyName());

        List<OrgAgreementDto> list = new ArrayList<>();
        if (role == 0)
            list = agreementMapper.getOrgAgreementList(params);
        else
            list = agreementMapper.getOrgAgreementLists(params);
        for(OrgAgreementDto list1:list){
            if(new Date().getTime()>list1.getExpiredate().getTime()){
                list1.setExamState(3);
            }
        }
        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, agreementMapper.getOrgAgreementListCount(memberId), list.size() == pageSize)); }


    public ResponseParams<?> addAgreement() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String orgName = request.getParameter("orgName");
        String expireDate = request.getParameter("expireDate");
        String picList = request.getParameter("picList");
        String agreementId = request.getParameter("agreementId");

        if (memberMapper.getRoleByMemberId(memberId) != 0) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        if (StringUtils.isEmpty(orgName)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("orgName"));
        }
        if (StringUtils.isEmpty(expireDate)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("expireDate"));
        }
        if (StringUtils.isEmpty(picList)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("picList"));
        }

        List<String> picStr;
        try {
            picStr = JSONObject.parseArray(picList, String.class);
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.isDataError("json解析错误"));
        }


        Agreement agreement = new Agreement();
        agreement.setOrgId(orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id", memberId)).getOrgId());
        agreement.setExpireDate(getStringToDate(expireDate));
        agreement.setName(orgName);
        agreement.setPics(String.join(",", picStr));
        agreement.setExamState(0);

        if (StringUtils.isEmpty(agreementId)) {
            agreement.setCreateDate(new Date());
            agreementMapper.insert(agreement);
        } else {
            agreement.setId(Integer.valueOf(agreementId));
            agreement.setUpdateDate(new Date());
            agreementMapper.updateById(agreement);
        }


        return ResponseParams.ok(null);
    }


    public ResponseParams<?> deleteAgreement() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String agreementId = request.getParameter("agreementId");
        if (memberMapper.getRoleByMemberId(memberId) != 0) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        if (StringUtils.isEmpty(agreementId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("agreementId"));
        }
        agreementMapper.deleteById(agreementId);

        return ResponseParams.ok(null);
    }


    public ResponseParams<?> isOrgAgreementExpired() throws Exception{
        Integer memberId = ss.getCurrentUserId();
        String orgId = request.getParameter("orgId");
        Integer sys_org_id;
        String real_name;
        if (memberMapper.getRoleByMemberId(memberId) != 0) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }
        if(StringUtils.isEmpty(orgId)){
            throw RequestException.create(ResponseParams.isDataError("缺少orgId参数"));
        }
        sys_org_id = orgMapper.selectOrdId(memberId);
        real_name = orgMapper.getRealName(Integer.parseInt(orgId));
        OrgAgreementDto orgAgreementDto=agreementMapper.isOrgAgreementExpired(sys_org_id,real_name);
        Map<String,Object> map = new HashMap<>();
        if(orgAgreementDto!=null) {
            if (orgAgreementDto.getExpiredate().getTime()>new Date().getTime()) {
                map.put("state","Pass");
            }else{
                map.put("error","请签订有效协议");
            }
        }
        return ResponseParams.ok(map);
    }

    /*
     * 将时间戳转换为时间
     */
    public static Date getStringToDate(String time) throws Exception {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(format.format(new Long(Long.parseLong(time))));
            return date;
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }
    }


}
